import path from 'path';
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import Components from 'unplugin-vue-components/vite';
import ViteSvgIcon from 'vite-plugin-svg-icons';
import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers';
import Markdown from 'vite-plugin-md';
import copy from 'rollup-plugin-copy';
// import styleImport, { AndDesignVueResolve } from 'vite-plugin-style-import';
// import dts from 'vite-plugin-dts';

interface IArgs {
  mode: string
}
export default ({ mode }: IArgs) => {
  const env = loadEnv(mode, process.cwd());
  const isLib = env.VITE_APP_ENV === 'lib';

  // vite 插件
  const plugins = [
    vue({ include: [/\.vue$/, /\.md$/] }),
    Components({
      resolvers: [
        AntDesignVueResolver({
          resolveIcons: true,
          importStyle: 'less'
        })
      ],
      dts: true
    }),
    ViteSvgIcon({
      iconDirs: [path.resolve(__dirname, 'src/icon')],
      symbolId: 'icon-[dir]-[name]'
    }),
    Markdown()
  ];
  
  // vite build 配置
  const build: any = {
    outDir: isLib ? 'lib' : 'dist',
    cssCodeSplit: !isLib, // 是库环境就不分割css
  }
  if (isLib) {
    plugins.push(copy({
      targets: [
        { src: 'src/styles', dest: 'lib' },
        { src: 'src/utils', dest: 'lib' },
        { src: 'src/directive', dest: 'lib' },
        // { src: 'src/packages', dest: 'lib' },
      ],
      // 改变 插件执行时机
      hook: 'writeBundle'
    }))
    // 指定加类型的插件
    // plugins.push(dts())
    build.lib = {
      // 设置入口文件
      entry: path.resolve(__dirname, './src/packages/index.ts'),
      name: 'hitcxedu-ant-ui',
    }
    build.rollupOptions = {
      // 确保外部化处理那些你不想打包进库的依赖
      external: ['vue', 'vite-plugin-md', 'vue-router'],
      output: {
        // 在 UMD 构建模式下为这些外部化的依赖提供一个全局变量
        globals: {
          vue: 'Vue',
        }
      },
    }
  }
  return defineConfig({
    plugins,
    build,
    server: {
      host: true,
      port: 3002
    },
    css: {
      preprocessorOptions: {
        less: {
          javascriptEnabled: true
        }
      },
      postcss: {
        plugins: [
          // css自动添加浏览器前缀
          require('autoprefixer')({
            overrideBrowserslist: [
              'Android 4.1',
              'iOS 7.1',
              'Chrome > 31',
              'ff > 31',
              'ie >= 8',
              '> 1%'
            ],
            // 为 IE 启用网格布局前缀
            grid: true
          }),
          require('postcss-import')
        ]
      }
    },
    resolve: {
      alias: {
        '@': path.resolve(__dirname, 'src'),
        '@packages': path.resolve(__dirname, 'packages'),
      }
    }
  })
}